import { useState, useEffect } from "react"
import { Card, message } from "antd"
import { CopyOutlined, SyncOutlined } from "@ant-design/icons"

const FooterOnePhrase = () => {
  const [quote, setQuote] = useState({
    content: "加载中...",
    author: "",
    date: new Date().toLocaleDateString(),
    loading: true
  })

  // 获取每日一言
  const fetchQuote = async () => {
    setQuote(prev => ({...prev, loading: true}))
    try {
      // 生成签名密钥
      const signatureKey = `U2FsdGVkX1${Date.now()}`
      
      const response = await fetch('https://api.codelife.cc/yiyan/random?lang=cn', {
        headers: {
          'signaturekey': signatureKey,
          'origin': window.location.origin
        }
      })
      
      const result = await response.json()
      
      if (result.msg === '加载成功') {
        const data = result.data
        const now = new Date()
        const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
        
        setQuote({
          content: data.hitokoto || "今日无一言",
          author: data.from || "未知",
          date: `${now.getFullYear()}.${(now.getMonth()+1).toString().padStart(2,'0')}.${now.getDate().toString().padStart(2,'0')} ${days[now.getDay()]}`,
          loading: false
        })
      }
    } catch (error) {
      console.error('获取一言失败:', error)
      setQuote({
        content: "获取一言失败，点击刷新",
        author: "",
        date: new Date().toLocaleDateString(),
        loading: false
      })
    }
  }

  // 复制一言
  const handleCopy = () => {
    navigator.clipboard.writeText(`「${quote.content}」${quote.author ? `${quote.author}` : ''}`)
      .then(() => message.success('已复制到剪贴板'))
      .catch(() => message.error('复制失败'))
  }

  // 右键刷新一言
  const handleContextMenu = (e: React.MouseEvent) => {
    e.preventDefault()
    fetchQuote()
  }

  useEffect(() => {
    fetchQuote()
  }, [])

  return (
    <Card 
      title="每日一言" 
      size="small"
      style={{ marginTop: 16, cursor: 'pointer' }}
      extra={[
        <SyncOutlined 
          key="refresh" 
          onClick={fetchQuote}
          spin={quote.loading}
          style={{ marginRight: 8 }}
        />,
        <CopyOutlined 
          key="copy" 
          onClick={handleCopy}
        />
      ]}
      onContextMenu={handleContextMenu}
    >
      <p style={{ margin: 0 }}>{quote.date}</p>
      <p style={{ margin: '8px 0' }}>「{quote.content}」</p>
      {quote.author && (
        <p style={{ margin: 0, textAlign: "right" }}>{quote.author}</p>
      )}
    </Card>
  )
}

export default FooterOnePhrase